package com.taotaojs.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.taotaojs.mybootsuper.bean.BaseBean;
import com.taotaojs.mybootsuper.controller.MyComController;
import com.taotaojs.mybootsuper.mapper.MyComMapper;
import com.taotaojs.mybootsuper.service.IMyComService;
import com.taotaojs.mybootsuper.service.MyComService;
import com.taotaojs.util.StringUtil;

import java.util.*;

/**
 * @author: TaoTaojs
 * @Date: 2020/7/13 2:30 PM
 * @Description: <h1>自动生成代码</h1>
 * <h2>简介</h2>
 * 基于tkMapper自动生成代码的工具类
 * <h3>主要功能：</h3>
 * <ol>
 *     <li>基于tkMapper自动生成代码的工具类</li>
 * </ol>
 * @关联类:
 * @参考链接：
 * @History: <br/>
 * <author>        <time>                      <version>          <desc>
 * TaoTaojs        2020/7/13 2:30 PM                V1.0          基于tkMapper自动生成代码的工具类
 */
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtil.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 下划线命名转为驼峰命名
     *
     * @param para
     *        下划线命名的字符串
     */
    public static String underlineToHump(String para, String prefix) {
        para = para.replaceAll(prefix, "");
        StringBuilder result = new StringBuilder();
        String[] a = para.split("_");
        for (String s : a) {
            if (result.length() == 0) {
                result.append(s.toLowerCase());
            } else {
                result.append(s.substring(0, 1).toUpperCase());
                result.append(s.substring(1).toLowerCase());
            }
        }
        return result.toString();
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
//        System.out.println("提交前确保数据库有主键ID和disable弃用标注列");

//        String tableName = scanner("tb_menu");
//        String modelName = scanner("system");

        String tableName = "tb_user";
        String modelName = "system";

        String projectPath = System.getProperty("user.dir");
//        String outPath = projectPath + "/shxd-service/shxd-service-" + modelName;
        String outPath = projectPath + "/myboot-generator";
        String outJavaPath = outPath + "/src/main/java";
        String outResourcesPath = outPath + "/src/main/resources";

        String packageName = "com.taotaojs";
        String packagePath = "com/taotaojs/";

        //代码生成器
        AutoGenerator mpg = new AutoGenerator();

        //全局配置
        GlobalConfig gc = new GlobalConfig();

        gc.setOutputDir(outJavaPath);
        gc.setAuthor("TaoTaojs");
        gc.setOpen(false);
        //实体属性 Swagger2 注解
        gc.setSwagger2(true);
        gc.setBaseResultMap(true);
        gc.setEntityName("%sModel");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
//        覆盖原有文件打开
        gc.setFileOverride(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://122.112.181.133:3306/hospital2.0?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("xdyg123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setModuleName(modelName);
        pc.setEntity("pojo.model");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>(2);
                map.put("serviceName", underlineToHump(tableName, "tb_") + "Service");
                map.put("tempName", underlineToHump(tableName, "tb_"));
                this.setMap(map);
            }
        };

        String templatePath = "/template_plus/mapper.xml.vm" ;
        String entityPath = "/template_plus/entity.java.vm" ;
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return outResourcesPath + "/mapper/" + tableInfo.getEntityName().replace("Model", "") + "Mapper.xml";

            }
        });
        focList.add(new FileOutConfig(entityPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return outJavaPath + "/" + packagePath + modelName + "/pojo/model/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setController("template_plus/controller.java");
        templateConfig.setService("template_plus/service.java");
        templateConfig.setServiceImpl("template_plus/serviceImpl.java");
        templateConfig.setEntity(null);
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setTablePrefix("tb_");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setCapitalMode(false);
        strategy.setSuperEntityClass(BaseBean.class);
        strategy.setSuperMapperClass(MyComMapper.class.getName());
        strategy.setSuperControllerClass(MyComController.class);
        strategy.setSuperServiceClass(IMyComService.class);
        strategy.setSuperServiceImplClass(MyComService.class);
        strategy.setEntityLombokModel(true);
        strategy.setEntityBuilderModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        // 写于父类中的公共字段
        strategy.setInclude(tableName.split(","));
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute();
    }

}
